from PIL import Image

def split_image(image_path, block_height=768, overlap=64):
    """
    将长图片垂直分割成带重叠的块。
    """
    img = Image.open(image_path)
    width, height = img.size
    
    if height <= block_height:
        return [img]

    blocks = []
    y = 0
    while y < height:
        start_y = y
        end_y = min(height, y + block_height)
        
        box = (0, start_y, width, end_y)
        block = img.crop(box)
        blocks.append(block)
        
        if end_y == height:
            break
        y += block_height - overlap
            
    return blocks

def merge_images(image_blocks, original_height, overlap=64):
    """
    将处理后的图片块拼接成一张大图。
    """
    if not image_blocks or len(image_blocks) == 1:
        return image_blocks[0] if image_blocks else None

    final_width = image_blocks[0].size[0]
    result_img = Image.new('RGB', (final_width, original_height))

    current_y = 0
    for i, block in enumerate(image_blocks):
        block_w, block_h = block.size
        
        # 计算每个块需要粘贴的部分
        # 第一个块
        if i == 0:
            paste_h = block_h - overlap
            paste_region = block.crop((0, 0, block_w, paste_h))
        # 最后一个块
        elif i == len(image_blocks) - 1:
            paste_region = block.crop((0, overlap, block_w, block_h))
        # 中间块
        else:
            paste_region = block.crop((0, overlap, block_w, block_h - overlap))

        result_img.paste(paste_region, (0, current_y))
        current_y += paste_region.size[1]

    # 由于计算偏差，裁剪到原始高度
    return result_img.crop((0, 0, final_width, original_height))